<template>
  <header class="app-header">
    <!-- 左侧 -->
    <div class="header-left">
      <!-- 时间 -->
      <div class="time-module">
        <div class="time">{{ `${currentDate} ${currentTime}` }}</div>
      </div>
      <!-- 左侧的导航 -->
      <nav class="nav-tabs">
        <div
          v-for="tab in leftTabs"
          :key="tab.key"
          class="nav-tab"
          :class="{ 
            active: activeTab === tab.key,
            'has-dropdown': tab.children && tab.children.length > 0
          }"
          @click="handleTabClick(tab)"
          @mouseenter="handleMouseEnter(tab)"
          @mouseleave="handleMouseLeave"
        >
          <span>{{ tab.label }}</span>
          <!-- 二级菜单 -->
          <div
            v-if="tab.children && tab.children.length > 0"
            class="sub-menu"
            :class="{ show: activeDropdown === tab.key }"
            @mouseenter="handleDropdownMouseEnter"
            @mouseleave="handleDropdownMouseLeave"
          >
            <div
              class="sub-menu-item"
              v-for="child in tab.children"
              :key="child.key"
              @click.stop="handleSubItemClick(child)"
            >
              <span class="sub-menu-item-label">{{ child.label }}</span>
            </div>
          </div>
        </div>
      </nav>
    </div>

    <!-- 中间 -->
    <div class="header-center">
      <h1 class="app-title">{{ appTitle }}</h1>
    </div>

    <!-- 右侧 -->
    <div class="header-right">
      <!-- 右侧的导航 -->
      <nav class="nav-tabs">
        <div
          v-for="tab in rightTabs"
          :key="tab.key"
          class="nav-tab"
          :class="{
            active: activeTab === tab.key,
            'has-dropdown': tab.children && tab.children.length > 0,
          }"
          @click="handleTabClick(tab)"
          @mouseenter="handleMouseEnter(tab)"
          @mouseleave="handleMouseLeave"
        >
          <span>{{ tab.label }}</span>
          <!-- 二级菜单 -->
          <div
            v-if="tab.children && tab.children.length > 0"
            class="sub-menu"
            :class="{ show: activeDropdown === tab.key }"
            @mouseenter="handleDropdownMouseEnter"
            @mouseleave="handleDropdownMouseLeave"
          >
            <div
              class="sub-menu-item"
              v-for="child in tab.children"
              :key="child.key"
              @click.stop="handleSubItemClick(child)"
            >
              <span class="sub-menu-item-label">{{ child.label }}</span>
            </div>
          </div>
        </div>
      </nav>
      <!-- 用户信息 -->
      <div class="user-info">
        <span class="username">{{ `欢迎您！${username}` }}</span>
        <el-icon class="logout-icon" @click="handleLogout">
          <SwitchButton />
        </el-icon>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { ElMessageBox } from "element-plus";
import { SwitchButton } from "@element-plus/icons-vue";
import { appConfig } from "@/config";

const router = useRouter();
const userStore = useUserStore();

const currentDate = ref("");
const currentTime = ref("");
const activeTab = ref("home"); // 当前激活的导航栏
const activeDropdown = ref(null); // 当前激活的下拉菜单
const dropdownTimer = ref(null); // 下拉菜单延迟定时器

const appTitle = computed(() => appConfig.title); // 应用标题
const username = computed(() => userStore.userInfo?.username || "用户"); // 用户名

// 左侧导航栏
const leftTabs = [
  {
    key: "home",
    label: "首 页",
    path: "/dashboard",
  },
  {
    key: "live",
    label: "直 播",
    path: "/live"
  },
  {
    key: "monitor",
    label: "实时监管",
    path: "/monitor",
  },
];

// 右侧导航栏
const rightTabs = [
  {
    key: "data",
    label: "数据管理",
    path: "/dataManage",
  },
  {
    key: "route",
    label: "航线管理",
    path: "/airlineEdit",
  },
  {
    key: "app",
    label: "应用管理",
    path: "/appManage",
    children: [
      { key: "modelBase", label: "模型库", path: "/appManage/modelBase" },
      { key: "taskManage", label: "任务管理", path: "/appManage/taskManage" },
    ]
  },
];

// 时间更新定时器
let timer = null;

/**
 * 更新时间
 */
const updateDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  currentDate.value = `${year}-${month}-${day}`;
  currentTime.value = `${hours}:${minutes}:${seconds}`;
};

/**
 * 处理导航栏点击事件
 */
const handleTabClick = (tab) => {

  // 设置当前激活的tab
  activeTab.value = tab.key;

  // 无论是否有子菜单，都进行路由跳转
  if (tab.path && router.currentRoute.value.path !== tab.path) {
    router.push(tab.path).catch((err) => {
      console.error("路由跳转出错啦~:", err);
    });
  }
};

/**
 * 鼠标进入tab时
 */
const handleMouseEnter = (tab) => {
  // 清除之前的定时器
  if (dropdownTimer.value) {
    clearTimeout(dropdownTimer.value);
    dropdownTimer.value = null;
  }

  // 如果有子菜单，立即显示
  if (tab.children && tab.children.length > 0) {
    activeDropdown.value = tab.key;
  }
};

/**
 * 鼠标离开tab时
 */
const handleMouseLeave = () => {
  // 设置延迟关闭，给用户时间移动到下拉菜单
  dropdownTimer.value = setTimeout(() => {
    activeDropdown.value = null;
  }, 300); // 300ms延迟
};

/**
 * 鼠标进入下拉菜单时
 */
const handleDropdownMouseEnter = () => {
  // 清除关闭定时器，保持菜单显示
  if (dropdownTimer.value) {
    clearTimeout(dropdownTimer.value);
    dropdownTimer.value = null;
  }
};

/**
 * 鼠标离开下拉菜单时
 */
const handleDropdownMouseLeave = () => {
  // 延迟关闭
  dropdownTimer.value = setTimeout(() => {
    activeDropdown.value = null;
  }, 300);
};

/**
 * 处理子菜单点击事件
 */
const handleSubItemClick = (child) => {
  activeDropdown.value = null;
  if (child.path) {
    router.push(child.path).catch((err) => {
      console.error("子菜单路由跳转出错啦~:", err);
    });
  }
};

/**
 * 处理退出登录
 */
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm("确定要退出登录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await userStore.logout();
    router.push("/login");
  } catch {
    // 用户取消
  }
};

/**
 * 组件挂载时
 */
onMounted(() => {
  updateDateTime();
  timer = setInterval(updateDateTime, 1000);

  // 根据当前路由设置activeTab
  const currentPath = router.currentRoute.value.path;
  const allTabs = [...leftTabs, ...rightTabs];
  const matchedTab = allTabs.find((tab) => tab.path === currentPath);
  if (matchedTab) {
    activeTab.value = matchedTab.key;
  }
});

/**
 * 组件卸载时
 */
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }

  // 清除下拉菜单定时器
  if (dropdownTimer.value) {
    clearTimeout(dropdownTimer.value);
  }
});
</script>

<style lang="scss" scoped>
/* 头部 */
.app-header {
  height: 124px; /** UI图高度为119px，但是背景图距离顶部有5px的间距，所以设置为124px */
  background-image: url("@/assets/images/header_bg.png");
  background-repeat: no-repeat;
  background-position: center 5px;
  background-size: auto 119px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px 25px 0;
  box-sizing: border-box;
  position: relative;
  z-index: 100;
  pointer-events: auto;
}

/* 左侧 */
.header-left {
  display: flex;
  align-items: center;
  gap: 30px;
  flex: 1;
  transform: rotate(3deg);
  position: relative;
  bottom: -2px;
  // 左侧时间
  .time-module {
    margin-right: 53px;
    .time {
      font-size: 14px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 14px;
      color: rgba(255, 255, 255, 1);
    }
  }
  // 导航下的二级菜单
  .nav-tabs {
    .nav-tab {
      .sub-menu {
        transform: translateX(-50%) translateY(-10px) rotate(-3deg);
        &.show {
          transform: translateX(-50%) translateY(0) rotate(-3deg);
        }
      }
    }
  }
}

/* 右侧 */
.header-right {
  display: flex;
  align-items: center;
  gap: 30px;
  flex: 1;
  transform: rotate(-3deg);
  position: relative;
  bottom: -2px;
  justify-content: flex-end;
  // 右侧-用户信息
  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;

    .username {
      font-size: 14px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 20.27px;
      color: rgba(255, 255, 255, 1);
    }

    .logout-icon {
      font-size: 18px;
      color: rgba(255, 255, 255, 0.7);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        color: #00ffff;
        transform: rotate(180deg);
      }
    }
  }
  // 导航下的二级菜单
  .nav-tabs {
    .nav-tab {
      .sub-menu {
        transform: translateX(-50%) translateY(-10px) rotate(3deg);
        &.show {
          transform: translateX(-50%) translateY(0) rotate(3deg);
        }
      }
    }
  }
}

/* 中间 */
.header-center {
  flex: 0 0 auto;
  padding-top: 25px;
  box-sizing: border-box;
  // 应用标题
  .app-title {
    color: rgba(255, 255, 255, 1);
    text-shadow: 0px 2px 5px rgba(172, 248, 249, 0.5);
    font-size: 36px;
    font-weight: 700;
    letter-spacing: 2.25px;
    line-height: 36px;
  }
}

/* 导航栏 */
.nav-tabs {
  display: flex;
  gap: 45px;

  .nav-tab {
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 0px;
    line-height: 16px;
    color: #fff;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;

    &::after {
      content: "";
      position: absolute;
      bottom: -12px;
      left: 50%;
      transform: translateX(-50%);
      width: 0;
      height: 3px;
      background: linear-gradient(
        116.57deg,
        rgba(200, 200, 200, 0) 0%,
        rgba(0, 255, 244, 1) 51.27%,
        rgba(151, 151, 151, 0) 100%
      );
      transition: width 0.3s ease;
    }

    &:hover {
      color: rgba(0, 255, 244, 1);
    }

    &.active {
      color: rgba(0, 255, 244, 1);

      &::after {
        width: 70px;
      }
    }

    // 二级菜单
    .sub-menu {
      position: absolute;
      top: 100%;
      left: 50%;
      transform: translateX(-50%) translateY(-10px);
      margin-top: 15px;
      background: linear-gradient(
        270deg,
        rgba(22, 57, 65, 1) 0%,
        rgba(62, 163, 166, 1) 100%
      );
      border-radius: 7px;
      padding: 6px 4px;
      min-width: 127px;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
      z-index: 1000;

      &.show {
        opacity: 1;
        visibility: visible;
        transform: translateX(-50%) translateY(0);
      }

      .sub-menu-item {
        min-width: 120px;
        height: 30px;
        display: flex;
        flex-flow: row nowrap;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          border-radius: 4px;
          background: linear-gradient(
            180deg,
            rgba(25, 167, 181, 1) 0%,
            rgba(2, 48, 60, 1) 47.31%,
            rgba(102, 255, 255, 1) 100%
          );
        }

        .sub-menu-item-label {
          font-size: 14px;
          font-weight: 400;
          letter-spacing: 0px;
          line-height: 14px;
          color: rgba(255, 255, 255, 1);
        }
      }
    }
  }
}
</style>
